package cn.xiaobai.listener;

import cn.xiaobai.subscriber.RedisEventBusSubscriber;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author yangdaji
 * @Date 2023/11/2
 * @PackageName cn.xiaobai.listener
 * @ClassName RedisClientListener
 */
@Component
public class RedisClientListener {

    private static Map<String, RedisEventBusSubscriber> listeners = new ConcurrentHashMap<>();

    public void subscriber(String channel, RedisEventBusSubscriber redisEventBusSubscriber) {
        redisEventBusSubscriber.onSubscribe(channel);
        listeners.put(channel, redisEventBusSubscriber);
    }


    public void publish(String channel, String message) {
        RedisEventBusSubscriber redisEventBusSubscriber = listeners.get(channel);
        if (redisEventBusSubscriber != null) {
            redisEventBusSubscriber.onMessage(message);
        }
    }

    public void destroy(String channel) {
        RedisEventBusSubscriber redisEventBusSubscriber = listeners.get(channel);
        if (redisEventBusSubscriber != null) {
            redisEventBusSubscriber.onUnSubscribe(channel);
        }
    }
}
